package com.bysj.sausys.controller.backend;

import com.bysj.sausys.beans.PageQuery;
import com.bysj.sausys.beans.PageResult;
import com.bysj.sausys.common.JsonData;
import com.bysj.sausys.common.UserConst;
import com.bysj.sausys.service.ISysWorkFlowService;
import com.bysj.sausys.vo.TaskVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * 工作流的controller
 *
 * @author WangZK
 */
@Api(description = "工作流接口")
@Controller
@RequestMapping("/sys/workflow")
public class SysWorkFlowController {

    @Resource
    private ISysWorkFlowService sysWorkFlowService;

    private final String fileExtensionName = "zip";

    /**
     * 获取部署信息
     *
     * @return
     */
    @ApiOperation(value = "获取部署信息接口")
    @RequestMapping(value = "/getDeployInfo", method = RequestMethod.GET)
    @ResponseBody
    public JsonData getDeployInfo() {
        Map result = sysWorkFlowService.getDeployInfo();
        return JsonData.success(result);
    }

    /**
     * 发布流程
     *
     * @param zipFile
     * @param processDefinitionName
     * @param request
     * @return
     */
    @ApiOperation(value = "发布流程接口")
    @RequestMapping(value = "/saveDeployment", method = RequestMethod.POST)
    @ResponseBody
    public JsonData saveDeployment(@ApiParam(value = "流程定义zip文件", required = true) @RequestParam MultipartFile zipFile,
                                   @ApiParam(value = "流程定义名称", required = true) @RequestParam String processDefinitionName,
                                   HttpServletRequest request) {
        String fileExtensionName = zipFile.getOriginalFilename().substring(zipFile.getOriginalFilename().lastIndexOf(".") + 1);
        if (!this.fileExtensionName.equals(fileExtensionName)) {
            return JsonData.fail("文件格式错误，请上传zip压缩文件");
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        sysWorkFlowService.saveNewDeploy(zipFile, path, processDefinitionName);
        return JsonData.success();
    }

    /**
     * 删除部署信息
     *
     * @param deploymentId
     * @return
     */
    @ApiOperation(value = "删除部署信息接口")
    @RequestMapping(value = "/delDeployment", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonData delDeployment(@ApiParam(value = "部署ID", required = true) @RequestParam String deploymentId) {
        //使用部署对象ID，删除流程定义
        sysWorkFlowService.deleteProcessDefinitionByDeploymentId(deploymentId);
        return JsonData.success();
    }

    /**
     * 查看流程图
     *
     * @param deploymentId
     * @param diagramResourceName
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "查看流程图接口")
    @RequestMapping(value = "/viewImage", method = RequestMethod.GET)
    public void viewImage(@ApiParam(value = "部署ID", required = true) @RequestParam String deploymentId,
                          @ApiParam(value = "图片资源文件名称", required = true) @RequestParam String diagramResourceName,
                          HttpServletResponse response) throws IOException {
        //获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = sysWorkFlowService.findImageInputStream(deploymentId, diagramResourceName);
        //从response对象获取输出流
        OutputStream out = response.getOutputStream();
        //将输入流中的数据读取出来，写到输出流中
        for (int b = -1; (b = in.read()) != -1; ) {
            out.write(b);
        }
        out.close();
        in.close();
    }

    /**
     * 获取图片的Url
     *
     * @param deploymentId
     * @param diagramResourceName
     * @param request
     * @return
     */
    @ApiOperation(value = "获取图片url")
    @RequestMapping(value = "/getImageUrl", method = RequestMethod.GET)
    @ResponseBody
    public String getImageUrl(@ApiParam(value = "部署ID", required = true) @RequestParam String deploymentId,
                                @ApiParam(value = "图片资源文件名称", required = true) @RequestParam String diagramResourceName,
                                HttpServletRequest request) {
        String url = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +
                "/sys/workflow/viewImage?deploymentId=" + deploymentId + "&diagramResourceName=" + diagramResourceName;
        return url;
    }

    /**
     * 查看当前流程图
     *
     * @param taskId
     * @param request
     * @return
     */
    @ApiOperation(value = "查看当前流程图接口")
    @RequestMapping(value = "/viewCurrentImage", method = RequestMethod.GET)
    @ResponseBody
    public JsonData viewCurrentImage(@ApiParam(value = "任务ID", required = true) @RequestParam String taskId,
                                     HttpServletRequest request) {
        Map result = sysWorkFlowService.getCurrentImageInfo(taskId, request);
        return JsonData.success(result);
    }

    /**
     * 获取任务列表
     *
     * @param pageNo
     * @param pageSize
     * @param request
     * @return
     */
    @ApiOperation(value = "获取任务列表接口")
    @RequestMapping(value = "/getTaskList", method = RequestMethod.GET)
    @ResponseBody
    public JsonData getTaskList(@ApiParam(value = "页码") @RequestParam(required = false, defaultValue = "1") int pageNo,
                                @ApiParam(value = "每页显示条数") @RequestParam(required = false, defaultValue = "10") int pageSize,
                                HttpServletRequest request) {
        Map map = UserConst.getCurrentUser(request);
        PageResult<TaskVo> result = sysWorkFlowService.findTaskListByUsername(new PageQuery(pageNo, pageSize), UserConst.getCurrentUsername(map));
        return JsonData.success(result);
    }
}
